package com.ouyunc.oauth2.config.override;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ouyunc.common.constant.enums.ResponseCodeEnum;
import com.ouyunc.common.base.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author fangzhenxun
 * @Description: 用来解决认证过的用户访问无权限资源时的异常
 * @Version V1.0
 **/
public class IAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger log = LoggerFactory.getLogger(IAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.error("处理权限异常了:{}",e.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(ResponseCodeEnum.FORBIDDEN.code());
        response.getWriter().print(JSON.toJSONString(ResponseResult.error(ResponseCodeEnum.FORBIDDEN, e.getMessage()), SerializerFeature.WriteMapNullValue));
    }
}
